package cn.sylinx.hbatis.plugin.transaction;

import java.sql.Connection;

import cn.sylinx.hbatis.exception.HbatisException;
import cn.sylinx.hbatis.plugin.IPlugin;

public class TransactionIsolationPlugin implements IPlugin {

	private int transactionIsolation = -1;

	public TransactionIsolationPlugin() {
		this(Connection.TRANSACTION_READ_COMMITTED);
	}

	public TransactionIsolationPlugin(int transactionIsolation) {
		this.transactionIsolation = transactionIsolation;
	}

	public void setTransactionIsolation(int transactionIsolation) {
		this.transactionIsolation = transactionIsolation;
	}

	private void assertTransactionIsolation() {

		if (Connection.TRANSACTION_NONE != transactionIsolation
				&& Connection.TRANSACTION_READ_UNCOMMITTED != transactionIsolation
				&& Connection.TRANSACTION_READ_COMMITTED != transactionIsolation
				&& Connection.TRANSACTION_REPEATABLE_READ != transactionIsolation
				&& Connection.TRANSACTION_SERIALIZABLE != transactionIsolation) {
			throw new HbatisException("invalid transactionIsolation: " + transactionIsolation);
		}
	}

	@Override
	public boolean start(Object... objects) {
		assertTransactionIsolation();
		TransactionIsolationWrapper.ME.setTransactionIsolation(transactionIsolation);
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

}
